package com.times.happy_every_day.controller;

import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

@RestController
@RequestMapping("/wxjava/mp")
@Slf4j
public class WxjavaTestController {
    @Autowired
    private WxMpService wxMpService;

    @Value("${loveday}")
    private String loveDay; // 相恋那天

    @Value("${birthday}")
    private String birthday; // 生日

    @Value("${templateId}")
    private String templateId; // 模板id

    @Value("#{'${userIds}'.split(',')}")
    private List<String> userIds; // 用户id


    @GetMapping("sendTemplateMessage")
    public String sendTemplateMessage() throws WxErrorException {
        String result = "success";

        for (String userId : userIds) {
            // 创建模板消息，设置模板id、指定模板消息要发送的目标用户
            WxMpTemplateMessage wxMpTemplateMessage = WxMpTemplateMessage.builder()
                    .templateId(templateId)
                    .toUser(userId)
                    .build();

            //  获取当前日期 星期
            String date = DateUtil.formatDate(new Date()) + " " + getWeekDay();

            // 获取当前天气
            JSONObject lives = (JSONObject) getWeather().getJSONArray("forecasts").get(0);
            JSONObject weather = (JSONObject) lives.getJSONArray("casts").get(0);

            wxMpTemplateMessage.addData(new WxMpTemplateData("date", date, "#6666FF"));
            wxMpTemplateMessage.addData(new WxMpTemplateData("city", lives.getStr("city"), "#33CCFF"));

            wxMpTemplateMessage.addData(new WxMpTemplateData("dayweather", weather.getStr("dayweather"), "#3333CC"));
            wxMpTemplateMessage.addData(new WxMpTemplateData("nightweather", weather.getStr("nightweather"), "#3333CC"));
            wxMpTemplateMessage.addData(new WxMpTemplateData("daytemp", weather.getStr("daytemp"), "#0099FF"));
            wxMpTemplateMessage.addData(new WxMpTemplateData("nighttemp", weather.getStr("nighttemp"), "#0099FF"));

            wxMpTemplateMessage.addData(new WxMpTemplateData("loveday", loveDay(), "#FF0000"));
            wxMpTemplateMessage.addData(new WxMpTemplateData("birthday", birthday(), "#990033"));

            // 每日菜单 getMenu
            JSONArray data = getMenu().getJSONArray("data");
            wxMpTemplateMessage.addData(new WxMpTemplateData("menu", data.toString(), "#3300FF"));

            // 内容
            wxMpTemplateMessage.addData(new WxMpTemplateData("content",getloverstr().getJSONObject("data").getStr("text") , "#9966FF"));

            result = wxMpService.getTemplateMsgService().sendTemplateMsg(wxMpTemplateMessage);
        }

        // 发送模板消息，返回消息id
        return result;
    }


    @GetMapping("getWeather")
    public JSONObject getWeather() {
        String key = "ec2d8030df308731b3b96814ac571485";
        String url = "https://restapi.amap.com/v3/weather/weatherInfo?key=" + key + "&city=440100&extensions=all";
        String s = HttpUtil.get(url);
        JSONObject entries = new JSONObject(s);
        return entries;
    }


    private static JSONObject getMenu() {
        String token = "c79jl305617ic3qoigx76v9nxzwb78w1";
        String url = "https://eolink.o.apispace.com/eat222/api/v1/forward/chishenme?size=3";
        Map<String, String> headers = new HashMap<>();
        headers.put("X-APISpace-Token", token);
        headers.put("Authorization-Type", "apikey");
        String body = HttpRequest.get(url).addHeaders(headers).execute().body();
        JSONObject entries = new JSONObject(body);
        return entries;
    }


    private static JSONObject getloverstr() {
        String url = "https://api.shadiao.pro/chp";
        String data = HttpUtil.get(url);
        return new JSONObject(data);
    }


    private static String getWeekDay() {
        String[] weekDays = {"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"};
        Calendar calendar = Calendar.getInstance();
        return weekDays[calendar.get(Calendar.DAY_OF_WEEK) - 1];
    }


    private String loveDay() {
        Date date1 = DateUtil.parse(loveDay);
        // 相差一个月，31天
        long betweenDay = DateUtil.between(date1, new Date(), DateUnit.DAY);
        return String.valueOf(betweenDay);
    }

    private String birthday() {
        Date date1 = DateUtil.parse(birthday);
        // 相差一个月，31天
        long betweenDay = DateUtil.between(new Date(), date1, DateUnit.DAY);
        return String.valueOf(betweenDay);
    }

}
